﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
namespace GUI.GoiHang
{
    //hungvv xu ly
    public partial class frmXuLy : Form
    {
        #region Delegate
        public delegate void GetString(Boolean capnhat);
        public GetString GetData;
        public static bool CheckClose = false;
        #endregion

        #region khai báo khởi tạo
        public bool kiemtra = false;
        bool checkClose = false;
        bool check = false;
        Entities.GoiHang goihang;
        Entities.GoiHang temp;
        Entities.ChiTietGoiHang[] hienthi;
        Entities.ChiTietGoiHang[] tempcheck;
        Entities.ChiTietGoiHang chitietgoihang;
        Entities.LoaiHang[] loaihang;
        Entities.NhomHangHoa[] nhomhang;
        public DateTime date;
        string makho = "";
        string hanhDong;
        int soluong = 1;
        double tongnt;
        public frmXuLy()
        {
            InitializeComponent();
            this.SelectCaiDatKho();
            Entities.CaiDatKho kho = GUI.Entitystatic.ViewFile();
            makho = kho.MaKho;
            //makho = caidatkho[0].KeyValue;
            lblTieuDe.Text = Common.Constants.GoiHang.TieuDeXuLyThem;
            date = Common.StaticVariable.InterfaceObject.SelectDate();
            hanhDong = "Insert";
           // sbiMaKho.Content = Common.Constants.MaKho + makho;
        }
        double giaNhap ;
        double giaBanBuon ;
        double giaBanLe ;

        //select cai dat kho hang
        private SetupConfig.Variable[] caidatkho;
        private void SelectCaiDatKho()
        {
            try
            {
                SetupConfig.Variable vl = new SetupConfig.Variable();
                vl.HanhDong = "1";
                //vl.HanhDong = "2";
                System.Reflection.Assembly getfile = System.Reflection.Assembly.GetExecutingAssembly();
                vl.FileName = getfile.Location + ".config";
                //vl.KeyName = "ChatService";
               // caidatkho = SetupConfig.Config.GetConfig(vl);
                //txtMaKho.Text = list[0].KeyValue;
                //txtTenKho.Text = list[1].KeyValue;
            }
            catch (Exception ex)
            {
                string s = ex.Message;

            }
        }

        public frmXuLy(Entities.GoiHang goihang)
        {
            InitializeComponent();
            this.SelectCaiDatKho();
            Entities.CaiDatKho kho1 = GUI.Entitystatic.ViewFile();
            makho = kho1.MaKho;
            lblTieuDe.Text = Common.Constants.GoiHang.TieuDeXuLySua;
            temp = goihang;
            XuLyDuLieu(goihang);
            DLSua=goihang;
            SelectData1();
            date = Common.StaticVariable.InterfaceObject.SelectDate();
            Entities.ChiTietGoiHang[] chitiet = DanhSach;

            hienthi = chitiet;
            hanhDong = "Update";
        }

        public Entities.GoiHang DLSua
        {
            get;
            set;
        }
        public Entities.LoaiHang[] loaiHang
        {
            get;
            set;
        }
        public Entities.NhomHangHoa[] nhomHang
        {
            get;
            set;
        }
        #endregion

        #region nhóm Hàng
        private string TenNhomHang = string.Empty;
        private string MaNhomHang = string.Empty;
        private Entities.GetCombobox[] phongban = null;
        private void HienThiPhongBan(string maloaihang)
        {
            try
            {
                for (int i = 0; i < phongban.Length; i++)
                {
                    if (phongban[i].TenCotKhoaChinh == maloaihang)
                    {
                        cbxLoaiHang.SelectedItem = i;
                        break;
                    }
                    else
                    { continue; }
                }
            }
            catch (Exception)
            {
                cbxLoaiHang.Items.Clear();
                MaNhomHang = string.Empty;
                TenNhomHang = string.Empty;
            }
        }
        private void PhongBan()
        {
            try
            {
                cbxLoaiHang.Items.Clear();
                Entities.GetCombobox pb = new Entities.GetCombobox();
                pb.TenBang = "NhomHang";
                pb.TenCotKhoaChinh = "MaNhomHang";
                pb.TenCotTenHienThi = "TenNhomHang";
                phongban = Common.StaticVariable.InterfaceObject.SelectCombox(pb);
                Common.Utilities.XuLyComboBox(cbxLoaiHang, phongban, "TenCotTenHienThi", "TenCotKhoaChinh");
            }
            catch (Exception ex)
            {
                cbxLoaiHang.Items.Clear();
                string s = ex.Message;
            }
        }
        #endregion

        #region lấy id
        // xử lý ID
        public string getID()
        {
            string code = string.Empty;
            try
            {
                Entities.GetID id = new Entities.GetID();
                id.TableName = "GoiHang";
                Entities.GetID get = Common.StaticVariable.InterfaceObject.SelectID(id);
                if (get.ColumnName != null)
                {
                    code = Common.Utilities.ProcessID(get.ColumnName);
                }
                else
                { code = "GH_0001"; }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                code = "GH_0001";
            }
            return code;
        }
        #endregion

        #region validate
        // kiểm tra
        public bool Validate()
        {
            if (txtMaGoiHang.Text == "")
            {
                MessageBox.Show(Common.MSG.MSG13(lblMaGoiHang.Text.ToString()), Common.MSG.TieuDe);
                txtMaGoiHang.Focus();
                return false;
            }
            if (txtTenGoiHang.Text == "")
            {
                MessageBox.Show(Common.MSG.MSG13(lblTenGoiHang.Text.ToString()), Common.MSG.TieuDe);
                txtTenGoiHang.Focus();
                return false;
            }
            if (cbxLoaiHang.Text == "")
            {
                MessageBox.Show(Common.MSG.MSG13(lblLoaiHang.Text.ToString()), Common.MSG.TieuDe);
                cbxLoaiHang.Focus();
                return false;
            }
            if (txtGiaNhapGH.Text.Length == 0)
            {
                MessageBox.Show(Common.MSG.MSG13(lblGiaNhapGH.Text.ToString()), Common.MSG.TieuDe);
                txtGiaNhapGH.Focus();
                return false;
            }
            if (txtGiaBanBuonGH.Text == "")
            {
                MessageBox.Show(Common.MSG.MSG13(lblGiaBanBuonGH.Text.ToString()), Common.MSG.TieuDe);
                txtGiaBanBuonGH.Focus();
                return false;
            }
            if (txtGiaBanLeGH.Text == "")
            {
                MessageBox.Show(Common.MSG.MSG13(lblGiaBanLeGH.Text.ToString()), Common.MSG.TieuDe);
                txtGiaBanLeGH.Focus();
                return false;
            }
            //if (txtSoLuong.Text == "")
            //{
            //    MessageBox.Show(Common.MSG.MSG13(label7.Text.ToString()), Common.MSG.TieuDe);
            //    txtSoLuong.Focus();
            //    return false;
            //}
            return true;
        }
        #endregion

        #region xử lý dữ liệu and select data       
        //Entities.ChiTietGoiHang chitietgoihang;
        public string magoihang = "";
        public void XuLyDuLieu(Entities.GoiHang goihang)
        {
            try
            {
                magoihang = goihang.MaGoiHang;
                txtMaGoiHang.Text = goihang.MaGoiHang;
                txtTenGoiHang.Text = goihang.TenGoiHang;
                MaNhomHang = goihang.MaNhomHang;
                TenNhomHang = goihang.TenNhomHang;
                txtGiaNhapGH.Text = goihang.GiaNhap;
                txtGiaBanBuonGH.Text = goihang.GiaBanBuon;
                txtGiaBanLeGH.Text = goihang.GiaBanLe;
                dtpHanSuDung.Text = DateTime.Now.ToShortDateString();
                txtGhiChu.Text = goihang.GhiChu;

            }
                
            catch { }
        }
        public void SelectData1()
        {
            try
            {
                if (DLSua != null) 
                {
                    magoihang = DLSua.MaGoiHang;
                    txtMaGoiHang.Text = DLSua.MaGoiHang;
                    txtTenGoiHang.Text = DLSua.TenGoiHang;
                    MaNhomHang = DLSua.MaNhomHang;
                    TenNhomHang = DLSua.TenNhomHang;
                    HienThiPhongBan(DLSua.MaNhomHang);
                    txtGiaNhapGH.Text = DLSua.GiaNhap;
                    txtGiaBanBuonGH.Text = DLSua.GiaBanBuon;
                    txtGiaBanLeGH.Text = DLSua.GiaBanLe;
                    dtpHanSuDung.Text = DateTime.Now.ToShortDateString();
                    txtGhiChu.Text = DLSua.GhiChu;
                }
                else
                {
                }
            }

            catch { }
        }
        private void cbxLoaiHang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Entities.GetCombobox row = (Entities.GetCombobox)cbxLoaiHang.SelectedValue;
                this.MaNhomHang = row.TenCotKhoaChinh;
                this.TenNhomHang = row.TenCotTenHienThi;
            }
            catch (Exception)
            {
                this.MaNhomHang = string.Empty;
                this.TenNhomHang = string.Empty;
            }
        }

        #endregion

        #region xử lý object
        public string gianhap = "";
        public string giabanbuon = "";
        public string giabanle = "";
        public Entities.GoiHang XuLyObject(string hanhdong)
        {
            try
            {
                if (Validate())
                {
                    goihang = new Entities.GoiHang();
                    goihang.HanhDong = hanhdong;
                    goihang.MaGoiHang = txtMaGoiHang.Text;
                    goihang.TenGoiHang = txtTenGoiHang.Text;
                    goihang.MaNhomHang = this.MaNhomHang;
                    goihang.TenNhomHang = this.TenNhomHang;
                    goihang.GiaNhap = txtGiaNhapGH.Text;
                    goihang.GiaBanBuon = txtGiaBanBuonGH.Text;
                    goihang.GiaBanLe = txtGiaBanLeGH.Text;
                    goihang.HanSuDung = DateTime.Parse(dtpHanSuDung.Text);
                    goihang.GhiChu = txtGhiChu.Text;
                    goihang.Deleted = false;
                    //goihang.TaiKhoan = UtilitiesVariable.User;
                    return goihang;
                }
                else
                {
                }
                 return null;
            }
            catch
            {
                return null;
            }
        
        }
        #endregion

        #region Xử lý thêm sửa
        void XulyThemSua()
        {
            if (hanhDong == "Insert")
                GhiLai();
            else
                Sua();
        }
        #endregion

        Entities.ChiTietGoiHang save;
        #region Sửa LV
        int i;
        DateTime hansudung;
        void SuaRow()
        {

            if (i < 0)
                return;
            if (dgvHienThi.RowCount > 1)
            {
                txtMaGoiHang.Text = dgvHienThi["MaGoiHang", i].Value.ToString().ToUpper();
                txtMaHangHoa.Text = dgvHienThi["MaHangHoa", i].Value.ToString().ToUpper();
                txtTenHang.Text = dgvHienThi["TenHangHoa", i].Value.ToString();
                txtGiaNhap.Text = dgvHienThi["GiaNhap", i].Value.ToString();
                txtGiaBanBuon.Text = dgvHienThi["GiaBanBuon", i].Value.ToString();
                txtGiaBanLe.Text = dgvHienThi["GiaBanLe", i].Value.ToString();
                txtSoLuong.Text = dgvHienThi["SoLuong", i].Value.ToString();
                tempcheck = new Entities.ChiTietGoiHang[dgvHienThi.RowCount - 1];
                int sotang = 0;
                for (int j = 0; j < dgvHienThi.RowCount; j++)
                {
                    if (dgvHienThi["MaHangHoa", j].Value.ToString() != dgvHienThi["MaHangHoa", i].Value.ToString())
                    {
                        tempcheck[sotang] = new Entities.ChiTietGoiHang("Delete", 0,
                 dgvHienThi["MaGoiHang", j].Value.ToString(), dgvHienThi["MaHangHoa", j].Value.ToString(),
                 dgvHienThi["TenHangHoa", j].Value.ToString(),
                 dgvHienThi["GiaNhap", j].Value.ToString(), dgvHienThi["GiaBanBuon", j].Value.ToString(),
                 dgvHienThi["GiaBanLe", j].Value.ToString(), int.Parse(dgvHienThi["SoLuong", j].Value.ToString()),
                 DateTime.Now,false
                 );
                        sotang++;
                    }
                }
                dgvHienThi.DataSource = tempcheck;
            }
            else
            {
                txtMaGoiHang.Text = dgvHienThi["MaGoiHang", i].Value.ToString().ToUpper();
                txtMaHangHoa.Text = dgvHienThi["MaHangHoa", i].Value.ToString().ToUpper();
                txtTenHang.Text = dgvHienThi["TenHangHoa", i].Value.ToString();
                txtGiaNhap.Text = dgvHienThi["GiaNhap", i].Value.ToString();
                txtGiaBanBuon.Text = dgvHienThi["GiaBanBuon", i].Value.ToString();
                txtGiaBanLe.Text = dgvHienThi["GiaBanLe", i].Value.ToString();
                txtSoLuong.Text = dgvHienThi["SoLuong", i].Value.ToString();
                dgvHienThi.DataSource = new Entities.ChiTietGoiHang[0];
               // txtMaHangHoa.Text = txtTenHang.Text = txtGiaNhap.Text = txtGiaBanBuon.Text = txtGiaBanLe.Text = txtSoLuong.Text = "0";
            }
          //  DeletRow();

        }
        #endregion

        #region Thêm Mới LV
        public void NewRow()
        {
            try
            {
                bool kt1 = false;

                int sohangtrongbang;
                hienthi = (Entities.ChiTietGoiHang[])dgvHienThi.DataSource;
                // list view = null
                if (hienthi == null)
                {
                    string sl = "0";
                    if (txtSoLuong.Text == "")
                        sl = "1";
                    else
                        sl = txtSoLuong.Text;
                    string soluongsp = sl + soluong;

                    //giá nhập
                    string gianhap = "0";
                    gianhap = txtGiaNhap.Text;
                    double gianhapsp = double.Parse(gianhap) * soluong;
                    //giá bán buôn
                    string giabanbuon = "0";
                    giabanbuon = txtGiaBanBuon.Text;
                    double giabanbuonsp = double.Parse(giabanbuon) * soluong;
                    //giá bán lẻ
                    string giabanle = "0";
                    giabanle = txtGiaBanLe.Text;
                    double giabanlesp = double.Parse(giabanle) * soluong;

                    tempcheck = new Entities.ChiTietGoiHang[1];
                    tempcheck[0] = new Entities.ChiTietGoiHang("Insert", 0, txtMaGoiHang.Text, txtMaHangHoa.Text,
                        txtTenHang.Text, gianhapsp.ToString(), giabanbuonsp.ToString(), giabanlesp.ToString(), 
                        int.Parse(sl),DateTime.Now,false);
                    dgvHienThi.DataSource = tempcheck;
                    return;
                }

                sohangtrongbang = hienthi.Length;
                // số lượng bảng ghi khác 0
                if (sohangtrongbang != 0)
                {
                    for (int j = 0; j < sohangtrongbang; j++)
                    {
                        // nếu tìm được mã đã có trong list view
                        if (mahanghoa == hienthi[j].MaHangHoa)
                        {
                            tempcheck = new Entities.ChiTietGoiHang[sohangtrongbang];
                            break;
                        }
                        // nếu không tìm được
                        else
                            tempcheck = new Entities.ChiTietGoiHang[sohangtrongbang + 1];
                    }
                }
                // số lượng bảng ghi = 0
                else
                    tempcheck = new Entities.ChiTietGoiHang[sohangtrongbang + 1];
                // nếu số lượng bảng ghi khác 0
                if (tempcheck.Length != 0)
                {
                    try
                    {
                        // số lượng bảng ghi = số lượng row list view
                        if (tempcheck.Length == hienthi.Length)
                        {
                            for (int j = 0; j < tempcheck.Length; j++)
                            {
                                // nếu mã = mã trong list view
                                if (mahanghoa == hienthi[j].MaHangHoa)
                                {
                                    int soluongcu = Convert.ToInt32(hienthi[j].SoLuong);
                                    string sl = "0";
                                    if (txtSoLuong.Text == "")
                                        sl = "1";
                                    else
                                        sl = txtSoLuong.Text;
                                    int soluongmoi = Convert.ToInt32(sl);
                                    int soluonghientai = soluongcu + soluongmoi;
                                    //giá nhập
                                    string gianhap = "0";
                                    gianhap = txtGiaNhap.Text;
                                    double gianhapmoi = double.Parse(gianhap);
                                    double gianhaphientai = gianhapmoi * soluonghientai;
                                    // giá bán buôn
                                    string giabanbuon = "0";
                                    giabanbuon = txtGiaBanBuon.Text;
                                    double giabanbuonmoi = double.Parse(giabanbuon);
                                    double giabanbuonhientai = giabanbuonmoi * soluonghientai;
                                    // giá bán lẻ
                                    string giabanle = "0";
                                    giabanle = txtGiaBanLe.Text;
                                    double giabanlemoi = double.Parse(giabanle);
                                    double giabanlehientai = giabanlemoi * soluonghientai;
                                    //
                                    tempcheck[j] = new Entities.ChiTietGoiHang("Insert", 0, txtMaGoiHang.Text,
                                        txtMaHangHoa.Text, txtTenHang.Text, gianhaphientai.ToString(),
                                        giabanbuonhientai.ToString(), giabanlehientai.ToString(), soluonghientai,DateTime.Now,false);
                                }
                                // nếu mã không = mã trong list view
                                else
                                    tempcheck[j] = new Entities.ChiTietGoiHang("Insert", 0, hienthi[j].MaGoiHang, 
                                        hienthi[j].MaHangHoa, hienthi[j].TenHangHoa, hienthi[j].GiaNhap, 
                                        hienthi[j].GiaBanBuon, hienthi[j].GiaBanLe, hienthi[j].SoLuong,hienthi[j].HanSuDung,hienthi[j].Deleted);

                            }
                        }
                        // số lượng bảng ghi không = số lượng row list view
                        else
                        {
                            for (int j = 0; j < tempcheck.Length; j++)
                            {
                                // lấy lại số bảng ghi trên list view
                                if (j < tempcheck.Length - 1)
                                    tempcheck[j] = new Entities.ChiTietGoiHang("Insert", hienthi[j].ChiTietGoiHangID,
                                        hienthi[j].MaGoiHang, hienthi[j].MaHangHoa, hienthi[j].TenHangHoa,
                                        hienthi[j].GiaNhap, hienthi[j].GiaBanBuon, hienthi[j].GiaBanLe, 
                                        hienthi[j].SoLuong,hienthi[j].HanSuDung,hienthi[j].Deleted);
                                // bảng ghi cuối cùng là mới insert vào
                                else
                                {
                                    string sl = "0";
                                    if (txtSoLuong.Text == "")
                                        sl = "1";
                                    else
                                        sl = txtSoLuong.Text;
                                    string soluongsp = sl + soluong;
                                    //giá nhập
                                    string gianhap = "0";
                                    gianhap = txtGiaNhap.Text;
                                    double gianhapsp = double.Parse(gianhap) * soluong;
                                    // giá bán buôn
                                    string giabanbuon = "0";
                                    giabanbuon = txtGiaBanBuon.Text;
                                    double giabanbuonsp = double.Parse(giabanbuon) * soluong;
                                    // giá bán lẻ
                                    string giabanle = "0";
                                    giabanle = txtGiaBanLe.Text;
                                    double giabanlesp = double.Parse(giabanle) * soluong;


                                    tempcheck[tempcheck.Length - 1] = new Entities.ChiTietGoiHang("Insert", 0, 
                                        txtMaGoiHang.Text, txtMaHangHoa.Text, txtTenHang.Text,
                                        gianhapsp.ToString(), giabanbuonsp.ToString(), giabanlesp.ToString(),
                                        int.Parse(sl),DateTime.Now,false);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        string sl = "0";
                        if (txtSoLuong.Text == "")
                            sl = "1";
                        else
                            sl = txtSoLuong.Text;
                        string soluongsp = sl + soluong;
                        //giá nhập
                        string gianhap = "0";
                        gianhap = txtGiaNhap.Text;
                        double gianhapsp = double.Parse(gianhap) * soluong;
                        // giá bán buôn
                        string giabanbuon = "0";
                        giabanbuon = txtGiaBanBuon.Text;
                        double giabanbuonsp = double.Parse(giabanbuon) * soluong;
                        // giá bán lẻ
                        string giabanle = "0";
                        giabanle = txtGiaBanLe.Text;
                        double giabanlesp = double.Parse(giabanle) * soluong;

                        tempcheck[tempcheck.Length - 1] = new Entities.ChiTietGoiHang("Insert", 0,
                            txtMaGoiHang.Text, txtMaHangHoa.Text, txtTenHang.Text, 
                            gianhapsp.ToString(), giabanbuonsp.ToString(), giabanlesp.ToString(), int.Parse(sl),DateTime.Now,false);
                    }
                    dgvHienThi.DataSource = tempcheck;
                }
            }
            catch
            {
                string sl = "0";
                if (txtSoLuong.Text == "")
                    sl = "1";
                else
                    sl = txtSoLuong.Text;
                string soluongsp = sl + soluong;
                //giá nhập
                string gianhap = "0";
                gianhap = txtGiaNhap.Text;
                double gianhapsp = double.Parse(gianhap) * soluong;
                // giá bán buôn
                string giabanbuon = "0";
                giabanbuon = txtGiaBanBuon.Text;
                double giabanbuonsp = double.Parse(giabanbuon) * soluong;
                //giá bán lẻ
                string giabanle = "0";
                giabanle = txtGiaBanLe.Text;
                double giabanlesp = double.Parse(giabanle) * soluong;

                tempcheck = new Entities.ChiTietGoiHang[1];
                tempcheck[0] = new Entities.ChiTietGoiHang("Insert", 0, txtMaGoiHang.Text,
                    txtMaHangHoa.Text, txtTenHang.Text,
                    gianhapsp.ToString(), giabanbuonsp.ToString(),
                    giabanlesp.ToString(), int.Parse(sl),DateTime.Now,false);
                dgvHienThi.DataSource = tempcheck;
            }
            finally
            {
                soluong = 1;
            }
        }
        #endregion

        #region tính toán
        void tinhgianhap()
        {
            tempcheck = (Entities.ChiTietGoiHang[])dgvHienThi.DataSource;
            double tonggianhap = 0;
            foreach (Entities.ChiTietGoiHang item in tempcheck)
            {
                tonggianhap += double.Parse(item.GiaNhap);

            }
            gianhap = tonggianhap.ToString();
        }
        void tinhgiabanbuon()
        {
            tempcheck = (Entities.ChiTietGoiHang[])dgvHienThi.DataSource;
            double tonggiabanbuon = 0;
            foreach (Entities.ChiTietGoiHang item in tempcheck)
            {
                tonggiabanbuon += double.Parse(item.GiaBanBuon);
            }
            giabanbuon = tonggiabanbuon.ToString();
        }
        void tinhgiabanle()
        {
            tempcheck = (Entities.ChiTietGoiHang[])dgvHienThi.DataSource;
            double tonggiabanbuon = 0;
            foreach (Entities.ChiTietGoiHang item in tempcheck)
            {
                tonggiabanbuon += double.Parse(item.GiaBanLe);

            }
            giabanle = tonggiabanbuon.ToString();
        }
        #endregion

        string mahanghoa;
        #region Ghi Lại
        void GhiLai()
        {
            try
            {
                if (check)
                {
                    check = false;
                    return;
                }

                goihang = XuLyObject("Insert");
                tempcheck = (Entities.ChiTietGoiHang[])dgvHienThi.DataSource;
                // check object
                if (goihang == null)
                {
                    MessageBox.Show(Common.MSG.MSG35(), Common.MSG.TieuDe);
                    return;
                }
                // check object
                if (tempcheck == null || tempcheck.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG35(), Common.MSG.TieuDe);
                    //SelectData1();
                    return;
                }

                //// check conflic insert
                if (!CheckConflicInsert(txtMaGoiHang.Text))
                {
                    MessageBox.Show(Common.MSG.MSG5(goihang.MaGoiHang), Common.MSG.TieuDe);
                    return;
                }
                // check insert
                if (Common.StaticVariable.InterfaceObject.InsertUpdateGoiHang(goihang) == 0)
                {
                    MessageBox.Show(Common.MSG.MSG15(goihang.MaGoiHang), Common.MSG.TieuDe);
                    Common.StaticVariable.InterfaceObject.DeletedGoiHang(goihang);
                    return;
                }

                // check insert details
                if (Common.StaticVariable.InterfaceObject.InsertUpdateChiTietGoiHang(tempcheck) == 0)
                {
                    MessageBox.Show(Common.MSG.MSG15(goihang.MaGoiHang), Common.MSG.TieuDe);
                    Entities.ChiTietGoiHang delete = new Entities.ChiTietGoiHang();
                    delete.MaGoiHang = magoihang;
                    Common.StaticVariable.InterfaceObject.DeletedChiTietGoiHang(delete);
                    return;
                }
                checkClose = true;
                goihang = null;
                check = true;
                GetData(true);
                this.Close();
            }
            catch
            {
            }
        }
        #endregion

        #region Check Conflic Insert
        public bool CheckConflicInsert(string goihang)
        {
            try
            {
                Entities.GoiHang hh = new Entities.GoiHang();
                //hh.HanhDong = "1";
                hh.MaGoiHang = goihang;
                Entities.GoiHang[] hharr = Common.StaticVariable.InterfaceObject.SelectGoiHangTheoMa(hh);
                if (hharr != null)
                {
                    if (hharr.Length != 0)
                        return false;
                    else
                    {
                        return true;
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region Sửa
        void Sua()
        {
            try
            {

                if (check)
                {
                    check = false;
                    return;
                }
                tinhgianhap();
                tinhgiabanbuon();
                tinhgiabanle();
                goihang = XuLyObject("Update");
                tempcheck = (Entities.ChiTietGoiHang[])dgvHienThi.DataSource;
                // check object
                if (goihang == null)
                {
                    return;
                }
                // check object
                if (tempcheck == null || tempcheck.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG35(), Common.MSG.TieuDe);
                    return;
                }
                Entities.CheckRefer cr = new Entities.CheckRefer();
                cr.MaTruong = goihang.MaGoiHang;
                cr.TenTruong = "GoiHang";
                if (!Common.StaticVariable.InterfaceObject.CheckRefer(cr))
                {
                    MessageBox.Show(cr.MaTruong + " đã có giao dịch không thể sửa", Common.MSG.TieuDe);
                    return;
                }
                // check conflic insert
                if (!CheckConflicUpdate())
                {
                    MessageBox.Show(Common.MSG.MSG6(), Common.MSG.TieuDe);
                    return;
                }
                // check insert
                if (Common.StaticVariable.InterfaceObject.InsertUpdateGoiHang(goihang) == 0)
                {
                    MessageBox.Show(Common.MSG.MSG17(goihang.MaGoiHang), Common.MSG.TieuDe);
                    Common.StaticVariable.InterfaceObject.DeletedGoiHang(goihang);
                    return;
                }
                // delete details
                Entities.ChiTietGoiHang delete = new Entities.ChiTietGoiHang();
                delete.MaGoiHang = goihang.MaGoiHang;
                if (Common.StaticVariable.InterfaceObject.DeletedChiTietGoiHang(delete) == 0) 
                {

                }
                // check insert details
                foreach (Entities.ChiTietGoiHang item in tempcheck)
                {
                    item.HanhDong = "Insert";
                }
                if (Common.StaticVariable.InterfaceObject.InsertUpdateChiTietGoiHang(tempcheck) == 0)
                {
                    MessageBox.Show(Common.MSG.MSG15(goihang.MaGoiHang), Common.MSG.TieuDe);
                    Entities.ChiTietGoiHang deleteerror = new Entities.ChiTietGoiHang();
                    delete.MaGoiHang = magoihang;
                    Common.StaticVariable.InterfaceObject.DeletedChiTietGoiHang(deleteerror);
                    return;
                }
                checkClose = true;
                goihang = null;
                check = true;
                GetData(true);
                this.Close();

            }
            catch
            {
            }
        }
        #endregion

        #region Check Conflic Update
        public bool CheckConflicUpdate()
        {
            try
            {
                Entities.GoiHang[] mangchitiet = Common.StaticVariable.InterfaceObject.SelectGoiHang(goihang);
                for (int i = 0; i < mangchitiet.Length; i++)
                {
                    if (mangchitiet[i].MaGoiHang == temp.MaGoiHang)
                    {
                        return Check(mangchitiet[i]);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }


        public bool Check(Entities.GoiHang goihang)
        {
            bool kt = true;
            if (temp.TenGoiHang != goihang.TenGoiHang)
            {
                txtTenGoiHang.Text = temp.TenGoiHang = goihang.TenGoiHang;
                kt = false;
            }
            return kt;
        }
        #endregion

        #region Thoát
        void Thoat()
        {
            try
            {
                System.Windows.Forms.DialogResult ketqua = System.Windows.Forms.MessageBox.Show("Bạn có chắc chắn muốn thoát không ?", "Thông báo", System.Windows.Forms.MessageBoxButtons.YesNo);
                {
                    if (ketqua == System.Windows.Forms.DialogResult.Yes)
                    {
                        this.checkClose = true;
                        this.Close();
                    }
                }
            }
            catch (Exception)
            { }
        }
        #endregion

        #region Processing
        //lay ban ghi de sua hoac xem
        private void GetRow()
        {
            try
            {
                if (DanhSach == null) { return; }
                for (int i = 0; i < this.DanhSach.Length; i++)
                {
                    if (DanhSach[i].MaHangHoa == this.mahanghoa)
                    {
                        GoiHang = DanhSach[i];
                        break;
                    }
                    else
                    { continue; }
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion

        #region HienThi
        private Entities.ChiTietGoiHang[] DanhSach;
        private Entities.ChiTietGoiHang GoiHang = null;
        private void HienThi()
        {
            try
            {
                Entities.ChiTietGoiHang nv = new Entities.ChiTietGoiHang();
                nv.HanhDong = "3";
                nv.MaGoiHang = magoihang;
                DanhSach = Common.StaticVariable.InterfaceObject.SelectChiTietGoiHang(nv);
                dgvHienThi.DataSource = DanhSach;
                this.HienThiListview();
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                DanhSach = null;
                HienThiListview();
            }
        }

        private void HienThiListview()
        {
            try
            {
                if (DanhSach == null)
                {
                    Entities.ChiTietGoiHang[] nv = new Entities.ChiTietGoiHang[0];
                    dgvHienThi.DataSource = nv;
                }
                for (int i = 0; i < dgvHienThi.ColumnCount; i++)
                {
                    dgvHienThi.Columns[i].Visible = false;
                }

                dgvHienThi.Columns["MaHangHoa"].HeaderText = "mã hàng hóa";
                dgvHienThi.Columns["MaHangHoa"].Visible = true;
                dgvHienThi.Columns["TenHangHoa"].HeaderText = "Tên hàng hóa";
                dgvHienThi.Columns["TenHangHoa"].Visible = true;
                dgvHienThi.Columns["GiaNhap"].HeaderText = "Giá nhập";
                dgvHienThi.Columns["GiaNhap"].Visible = true;
                dgvHienThi.Columns["GiaBanBuon"].HeaderText = "Giá Bán Buôn";
                dgvHienThi.Columns["GiaBanBuon"].Visible = true;
                dgvHienThi.Columns["GiaBanLe"].HeaderText = "Giá Bán Lẻ";
                dgvHienThi.Columns["GiaBanLe"].Visible = true;
                dgvHienThi.Columns["SoLuong"].HeaderText = "Số Lượng";
                dgvHienThi.Columns["SoLuong"].Visible = true;
                if (dgvHienThi.RowCount > 0)
                {
                    Common.Utilities.CountDatagridview(dgvHienThi);
                    dgvHienThi.Focus();
                    dgvHienThi.Select();
                }
                dgvHienThi.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvHienThi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion

        #region event form
        private void frmXuLy_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            PhongBan();
            try
            {
                if (this.hanhDong == "Update")
                {
                    txtMaGoiHang.Enabled = true;
                    txtGiaNhapGH.Enabled = false;
                    txtGiaBanBuonGH.Enabled = false;
                    txtGiaBanLeGH.Enabled = false;
                }
                txtMaGoiHang.Focus();
                this.FormClosing += new FormClosingEventHandler(frmXuLy_FormClosing);
                // key down
                txtMaHangHoa.KeyDown += new KeyEventHandler(txtmahanghoa_KeyUp);   
                txtSoLuong.KeyDown += new KeyEventHandler(txtsoluong_KeyUp);
                SelectData1();
                HienThi();
            }
            catch
            {
            }
        }
        private void btnThem_Click(object sender, EventArgs e)
        {
            NewRow();
            txtMaHangHoa.Text = null;
            txtTenHang.Text = null;
            txtGiaNhap.Text = null;
            txtGiaBanBuon.Text = null;
            txtGiaBanLe.Text = null;
            txtSoLuong.Text = null;
            txtMaHangHoa.Focus();
        }

        private void dgvHienThi_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                i = e.RowIndex;
            }
            catch { }
        }

        private void dgvHienThi_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                SuaRow();
            }
            catch { }
        }
        void frmXuLy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!checkClose)
                if (MessageBox.Show(Common.MSG.MSG2(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    e.Cancel = checkClose;
                else
                    e.Cancel = !checkClose;
            else
            {
                GetData(kiemtra);
            }
        }
        void txtmahanghoa_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyData == Keys.F4)
                {
                    if(Validate())
                    {
                        if (makho.Length == 0 || makho == "NULL")
                        {
                            MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe);
                            return;
                        }

                            TimKiem.frmHangHoa timkiem = new TimKiem.frmHangHoa(makho);
                            timkiem.ShowDialog();
                            if (TimKiem.frmHangHoa.selectedItem != null)
                            {
                                txtMaHangHoa.Text = mahanghoa = TimKiem.frmHangHoa.selectedItem.MaHangHoa;
                                txtTenHang.Text = TimKiem.frmHangHoa.selectedItem.TenHangHoa;
                                txtGiaNhap.Text = TimKiem.frmHangHoa.selectedItem.GiaNhap;
                                txtGiaBanBuon.Text = TimKiem.frmHangHoa.selectedItem.GiaBanBuon;
                                txtGiaBanLe.Text = TimKiem.frmHangHoa.selectedItem.GiaBanLe;
                                txtSoLuong.Focus();
                                TimKiem.frmHangHoa.selectedItem = null;
                            }
                    }
                }
            }
            catch
            {
            }
        }
        void txtsoluong_KeyUp(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.Enter)
            {
                if (txtSoLuong.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(label7.Text.ToString()), Common.MSG.TieuDe);
                    txtSoLuong.Focus();
                }
                    if (int.Parse(0 + txtSoLuong.Text) > 0)
                    {
                        mahanghoa = txtMaHangHoa.Text;
                        soluong = int.Parse(txtSoLuong.Text);
                        giaNhap += double.Parse(txtGiaNhap.Text) * soluong;
                        //lblTonggn.Content = Common.Constants.TongGN + giaNhap;
                        giaBanBuon += double.Parse(txtGiaBanBuon.Text) * soluong;
                        //lblTongbb.Content = Common.Constants.TongBB + giaBanBuon;
                        giaBanLe += double.Parse(txtGiaBanLe.Text) * soluong;
                        //lblTongbl.Content = Common.Constants.TongBL + giaBanLe;
                        NewRow();
                        txtMaHangHoa.Text = null;
                        txtTenHang.Text = null;
                        txtGiaNhap.Text = null;
                        txtGiaBanBuon.Text = null;
                        txtGiaBanLe.Text = null;
                        txtSoLuong.Text = null;
                        txtMaHangHoa.Focus();
                    }
                    else
                    {
                        MessageBox.Show("Số Lượng Phải Lớn Hơn 0");
                        txtSoLuong.Focus();
                    }
            }
        }
        public delegate void SelectData(string hanhdong);
        public SelectData Select;
        private void txtGiaNhapgh_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int i = int.Parse(txtGiaNhapGH.Text);
                if (i < 0)
                {
                    txtGiaNhapGH.Text = "";
                }
            }
            catch
            {
                txtGiaNhapGH.Text = "";
            }
        }
        private void txtGiaBanBuongh_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int i = int.Parse(txtGiaBanBuonGH.Text);
                if (i < 0)
                {
                    txtGiaBanBuonGH.Text = "";
                }
            }
            catch
            {
                txtGiaBanBuonGH.Text = "";
            }
        }
        private void txtGiaBanLegh_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int i = int.Parse(txtGiaBanLeGH.Text);
                if (i < 0)
                {
                    txtGiaBanLeGH.Text = "";
                }
            }
            catch
            {
                txtGiaBanLeGH.Text = "";
            }
        }

        private void txtSoLuong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int i = int.Parse(txtSoLuong.Text);
                if (i < 0)
                {
                    txtSoLuong.Text = "";
                }
            }
            catch
            {
                txtSoLuong.Text = "";
            }
        }
        private void btnGhiLai_Click(object sender, EventArgs e)
        {
            GhiLai();
        }
        private void btnThoat_Click(object sender, EventArgs e)
        {
            Thoat();
        }
        #endregion

       
      
    }
}
